package erediscluster

import (
	"context"
	"git.edaijia-inc.cn/edaijia/ego/elogger"
	"git.edaijia-inc.cn/edaijia/ego/etracer"
	"time"

	"github.com/go-redis/redis"
)

type RedisClusterConfig struct {
	Addr         []string `ini:"addr"`
	Password     string   `ini:"password"`
	DialTimeout  int      `ini:"dialtimeout"`
	ReadTimeout  int      `ini:"readtimeout"`
	WriteTimeout int      `ini:"writetimeout"`
	IdleTimeout  int      `ini:"idletimeout"`
}
type ERedisCluster struct {
	Config *RedisClusterConfig
	client *redis.ClusterClient
}

func InitERedisCluster(conf *RedisClusterConfig) *ERedisCluster {
	client := redis.NewClusterClient(&redis.ClusterOptions{
		Addrs:        conf.Addr,
		Password:     conf.Password,
		DialTimeout:  time.Duration(conf.DialTimeout) * time.Second,
		ReadTimeout:  time.Duration(conf.ReadTimeout) * time.Second,
		WriteTimeout: time.Duration(conf.WriteTimeout) * time.Second,
		IdleTimeout:  time.Duration(conf.IdleTimeout) * time.Minute,
		OnConnect: func(cn *redis.Conn) error {
			_, err := cn.Ping().Result()
			if err != nil {
				elogger.Error("redis cluster OnConnect error", err)
			}
			return err
		},
	})
	_, err := client.Ping().Result()
	if err != nil {
		elogger.Error("redis cluster OnConnect error", err)
	}
	return &ERedisCluster{conf, client}
}

func (e *ERedisCluster) Do(ctx context.Context, args ...interface{}) (result interface{}, err error) {
	etracer.ERedisSpanAround(
		ctx,
		e.Config.Addr[0],
		"Redis/EGO/GoRedisCluster/Do",
		func() error {
			result, err = e.client.Do(args...).Result()
			if err != nil && err != redis.Nil {
				return err
			}

			return nil
		},
		args...,
	)
	return
}
